#include "qNarackilista.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include <QDesktopWidget>


QNarackiLista::QNarackiLista(QWidget *parent)
	: QMyBaseFormWidget(parent)
	,m_offset(0)
{
	m_f3disabled = false;
	ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);
	ui.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
	ui.tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.tableView_2->setSelectionMode(QAbstractItemView::SingleSelection);
	ui.tableView_2->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.tableView->setSortingEnabled(true);
	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));
	ui.tableView_2->setSortingEnabled(true);
	connect(ui.tableView_2->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView_2, SLOT(sortByColumn(int)));

	ui.tableView_3->setSelectionMode(QAbstractItemView::SingleSelection);
	ui.tableView_3->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.tableView_3->setSortingEnabled(true);
	connect(ui.tableView_3->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView_3, SLOT(sortByColumn(int)));
	connect(ui.prevButton, SIGNAL(clicked()), this, SLOT(prevButtonPressed()));
	connect(ui.nextButton, SIGNAL(clicked()), this, SLOT(nextButtonPressed()));
	lista("%%%");
	m_selectedText = model->item(0, 0) ? model->item(0, 0)->text():"";
	lista_detail(m_selectedText);
	ui.tableView->setFocus();
	lista_detail(m_selectedText);

}

QNarackiLista::~QNarackiLista()
{

}
void QNarackiLista::pressEscape()
{
    emit closeW();
}
void QNarackiLista::lista(const QString& nameSearch)
{
    if (nameSearch.length() < 0)
    {
        ui.tableView->hide();
        return;
    }
    int r = 0;
    int c = 9;
    int fieldNo[9];
    QString country[9];
    int colWidth[] = {0, 80, 150, 200, 200, 200, 200, 0, 0};
    QString colName[] = {"id", "dok_id", "datum", "naziv", "adresa", "grad", "doc_creator", "dok_status", "dok_opis"};
    QString temp = 
        "select dokumenti.id, dok_id, datum, komintenti.naziv, komintenti.adresa, komintenti.grad, dokumenti.doc_creator, dokumenti.dok_status, dok_opis "
        "from dokumenti "
        "left join komintenti on dokumenti.komintent_id = komintenti.id "   
        "where dok_tip = 80 order by dok_id desc "
        ;
	temp += " limit 50 OFFSET "+ QString::number(m_offset, 10);
    QSqlQuery query(temp);
    model = new QStandardItemModel(r,c);
    model->setHeaderData( 0, Qt::Horizontal, trUtf8("Id."));
    model->setHeaderData( 1, Qt::Horizontal, trUtf8("Бр."));
    model->setHeaderData( 2, Qt::Horizontal, trUtf8("Датум"));
    model->setHeaderData( 3, Qt::Horizontal, trUtf8("Назив"));
    model->setHeaderData( 4, Qt::Horizontal, trUtf8("Адреса"));
    model->setHeaderData( 5, Qt::Horizontal, trUtf8("Град"));
    model->setHeaderData( 6, Qt::Horizontal, trUtf8("Нарачката за изработил-а"));

    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
    ui.tableView->setHorizontalHeader(header);
    header->show();
    int row = 0;
    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
            
            QStandardItem *item = new QStandardItem(query.value(i).toString());
            if ((i == 1))
            {
                if (query.value(7).toInt() == 0)
                {
                    QIcon ic1(":/sterna/Resources/ok.png");
                    item->setIcon(ic1);
                    item->setToolTip(trUtf8("Креирај налог за оваа нарачка"));
                }
                else
                {
                    QIcon ic1(":/sterna/Resources/stop.png");
                    item->setIcon(ic1);
                    item->setToolTip(trUtf8("Постои налог за оваа нарачка !!!"));
                }
            }

            item->setEditable(false);
            ui.tableView->setRowHeight(row, 18);
            ui.tableView->setColumnWidth(i, colWidth[i]);
            model->setItem(row, i, item);
        }
        row++;
    } 
    QItemSelectionModel *sm = ui.tableView->selectionModel();
    connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
        this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
    ui.tableView->show();
}
void QNarackiLista::selectionChanged(QModelIndex modelX, QModelIndex modelY)
{
    int i = modelX.row();
    m_selectedText = model->item(i, 1) ? model->item(i, 1)->text():"";
    ui.lineEdit_2->setText(model->item(i, 1)->text());
    ui.lineEdit->setText(model->item(i, 2)->text());
    ui.lineEdit_3->setText(model->item(i, 3)->text());
    ui.lineEdit_4->setText(model->item(i, 4)->text());
    ui.lineEdit_5->setText(model->item(i, 5)->text());
    ui.lineEdit_6->setText(model->item(i, 6)->text());
    ui.textEdit->setPlainText(model->item(i, 8)->text());
    if (model->item(i, 7)->text().toInt() == 0)
    {
        ui.pushButton_4->setEnabled(true);
		ui.pushButton_2->setEnabled(true);
		m_f3disabled = true;
    }
    else
    {
        ui.pushButton_4->setEnabled(false);
		ui.pushButton_2->setEnabled(false);
		m_f3disabled = false;
    }
    lista_detail(m_selectedText);
    
}
void QNarackiLista::lista_detail(const QString& nameSearch)
{
    QLocale loc;
    if (nameSearch.length() < 0)
    {
        ui.tableView_2->hide();
        return;
    }

    int r = 0;
    int c = 7;
    int fieldNo[7];
    QString country[7];
    int colWidth[] = {40, 70, 320, 70, 70, 70, 0};
    QString colName[] = {"id", "sifra", "artikal", "edm", "ikol", "icena", "proizvod_id"};
    QString temp = 
        "select artikli.id, sifra, artikal, edm, ikol, icena, magacin.proizvod_id "
        "from magacin                                         "
        "left join artikli on magacin.artikal_id = artikli.id "
        "where magacin.dok_tip = 80 and magacin.dok_id=       ";
    temp += m_selectedText;
    temp += "";
    QSqlQuery query(temp);

    model2 = new QStandardItemModel(r,c);
    model2->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид."));
    model2->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
    model2->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
    model2->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм."));
    model2->setHeaderData( 4, Qt::Horizontal, trUtf8("Количина"));
    model2->setHeaderData( 5, Qt::Horizontal, trUtf8("Цена"));
    ui.tableView_2->setModel(model2);
    header2 = new QHeaderView(Qt::Horizontal, this);
	header2->setClickable(true);
    ui.tableView_2->setHorizontalHeader(header2);
    header2->show();
    int row = 0;
    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
             fieldNo[i] = query.record().indexOf(colName[i]);
//             QStandardItem *item = new QStandardItem(query.value(fieldNo[i]).toString());
            QStandardItem *item = NULL;
            QString temp = query.value(fieldNo[i]).toString();
            if ((i > 3)&&(i < 6))
            {
                temp =  loc.toString(temp.toFloat(), 'f', 2);
                item = new QStandardItem(temp);
                item->setTextAlignment(Qt::AlignRight);
            }
            else
            {
                item = new QStandardItem(temp);
                item->setTextAlignment(Qt::AlignLeft);
            }

            item->setEditable(false);
            ui.tableView_2->setRowHeight(row, 18);
            ui.tableView_2->setColumnWidth(i, colWidth[i]);
            model2->setItem(row, i, item);
        }
        row++;
    } 
    ui.tableView_2->show();
	QItemSelectionModel *sm2 = ui.tableView_2->selectionModel();
	connect(sm2, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChangedTable2(QModelIndex,QModelIndex)));

	m_selectedText2 = model->item(0, 0) ? model->item(0, 0)->text():"";
	m_selectedText2_kolicina = model2->item(0, 4) ? model2->item(0, 4)->text() : "0";
	m_selectedText2_proizvodID = model2->item(0, 0) ? model2->item(0, 0)->text() : "0";
    lista_detail3(m_selectedText, m_selectedText2_kolicina, m_selectedText2_proizvodID);
}

void QNarackiLista::selectionChangedTable2(QModelIndex modelX, QModelIndex modelY)
{
	int i = modelX.row();
	m_selectedText2 = model->item(0, 0) ? model->item(0, 0)->text():"";
	m_selectedText2_kolicina = model2->item(i, 4) ? model2->item(i, 4)->text() : "0";
    m_selectedText2_proizvodID = model2->item(i, 6) ? model2->item(i, 6)->text() : "0";
	lista_detail3(m_selectedText, m_selectedText2_kolicina, m_selectedText2_proizvodID);
}

void QNarackiLista::deleteDok(int idDok)
{
    QSqlQuery query;
    query.clear();
    query.prepare(
        "delete from magacin where dok_tip = 80 and dok_id = :a"
        );
    query.bindValue(":a", idDok);	
    query.exec();
}
void QNarackiLista::on_pushButton_clicked()
{
    emit procF2();
}
void QNarackiLista::on_pushButton_2_clicked()
{
    emit procF3();
}

void QNarackiLista::on_pushButton_4_clicked()
{
    emit procF6();
}

QStringList QNarackiLista::geInfo()
{
    QStringList info;
    info.clear();
    info << ui.lineEdit_3->text() << ui.lineEdit_4->text() << ui.lineEdit_5->text() << ui.lineEdit->text()<< ui.lineEdit_2->text(); 
    return info;
}

void QNarackiLista::prevButtonPressed()
{
	m_offset = m_offset <= 50 ? 0 : m_offset - 50;
	lista("%%%");
}


void QNarackiLista::nextButtonPressed()
{
	m_offset += 50;
	lista("%%%");
}


void QNarackiLista::lista_detail3(const QString& nameSearch, const QString& nameSearch_kol,const QString& m_selectedText2_proizvodID)
{
	QLocale loc;
	if (nameSearch.length() < 0)
	{
		ui.tableView_2->hide();
		return;
	}

	int r = 0;
	int c = 5;
	int fieldNo[5];
	QString country[5];
	int colWidth[] = {0, 40, 450, 70, 80};
	QString colName[] = {"id", "sifra", "artikal", "edm", "kolicina"};
	QString temp = 
        " SELECT artikli.id, artikli.sifra, artikli.artikal, artikli.edm, magacin.ikol " 
        " FROM magacin " 
        " LEFT JOIN artikli ON artikli.id = magacin.artikal_id " 
        " WHERE dok_tip = 18 AND magacin.dok_id = "; 
	temp += nameSearch;
	temp += " and magacin.proizvod_id = '";
    temp += m_selectedText2_proizvodID + "'";
	QSqlQuery query(temp);

	model3 = new QStandardItemModel(r,c);
	model3->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид."));
	model3->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
	model3->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
	model3->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм."));
	model3->setHeaderData( 4, Qt::Horizontal, trUtf8("Количина"));
	ui.tableView_3->setModel(model3);
	header3 = new QHeaderView(Qt::Horizontal, this);
	header3->setClickable(true);
	ui.tableView_3->setHorizontalHeader(header3);
	header3->show();
	int row = 0;
	while (query.next()) 
	{
		for (int i = 0; i < c; i++)
		{
			fieldNo[i] = query.record().indexOf(colName[i]);
			//             QStandardItem *item = new QStandardItem(query.value(fieldNo[i]).toString());
			QStandardItem *item = NULL;
			QString temp = query.value(i).toString();
			if (i > 3)
			{
				temp =  loc.toString(temp.toFloat(), 'f', 2);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
			}
			else
			{
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignLeft);
			}

			item->setEditable(false);
			ui.tableView_3->setRowHeight(row, 18);
			ui.tableView_3->setColumnWidth(i, colWidth[i]);
			model3->setItem(row, i, item);
		}
		row++;
	} 
	ui.tableView_3->show();
}

void QNarackiLista::setRow(int mrow)
{
	ui.tableView->selectRow(mrow);
	ui.tableView->setFocus();
}
int QNarackiLista::getRow()
{
	int m_row = -1;
	QModelIndexList indexes = ui.tableView->selectionModel()->selection().indexes();
	if (indexes.count())
	{
		m_row = indexes.at(0).row();
	}
	return m_row;
}
